package com.sky.service.impl;

import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.service.OrderDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderDetailServiceImpl implements OrderDetailService {

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public Map<Long, List<OrderDetail>> getOrderDetailByOrdersIdList(List<Long> ordersIdList,
                                                                     Map<Long, Orders> ordersMap) {
        //根据订单idList批量查询每笔订单所对应的订单项
        List<OrderDetail> orderDetailList = orderDetailMapper.selectOrderDetailByOrdersIdList(ordersIdList);
        if (orderDetailList == null || orderDetailList.size() == 0) {
            return Collections.emptyMap();
        }

        //最终要返回的结果,Map中的key是orderId,Map中的value是每笔订单项
        Map<Long, List<OrderDetail>> result = new HashMap<>();

        //将每笔订单项进行分组,这样就能得到每笔订单所对应的订单项
        Map<Long, List<OrderDetail>> orderDetailMap = orderDetailList.stream().collect(Collectors.groupingBy(OrderDetail::getOrderId));
        for (Map.Entry<Long, List<OrderDetail>> entry : orderDetailMap.entrySet()) {
            if(!ordersMap.containsKey(entry.getKey())) continue;
            List<OrderDetail> orderDetails = entry.getValue();
            result.put(entry.getKey(), orderDetails);
        }
        return result;
    }
}
